/*
 * Copyright (c) 2014-2015 Luca Agostini, Alessandro Cantini, Alessandro Dignani
 *
 * This file is part of MeteoCal.
 *
 * MeteoCal is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package it.polimi.se2.agostini_cantini_dignani.meteocal.gui;

import it.polimi.se2.agostini_cantini_dignani.meteocal.business.CalendarManager;
import it.polimi.se2.agostini_cantini_dignani.meteocal.business.UserManager;
import it.polimi.se2.agostini_cantini_dignani.meteocal.entity.User;
import it.polimi.se2.agostini_cantini_dignani.meteocal.model.DatePattern;
import it.polimi.se2.agostini_cantini_dignani.meteocal.model.TemperatureUnit;
import it.polimi.se2.agostini_cantini_dignani.meteocal.model.TimePattern;
import it.polimi.se2.agostini_cantini_dignani.meteocal.util.DateTimeUtils;
import it.polimi.se2.agostini_cantini_dignani.meteocal.util.FacesMessenger;
import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;
import org.primefaces.model.UploadedFile;

import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.view.ViewScoped;
import javax.inject.Named;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.util.Arrays;
import java.util.List;
import java.util.TimeZone;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * @Author Alessandro Cantini
 */
@Named
@ViewScoped
public class SettingsBean implements Serializable {

	private static final Logger LOGGER = Logger.getLogger(SettingsBean.class.getName());

	private static final List<String> availableTimeZones = Arrays.asList(TimeZone.getAvailableIDs());
	private static final List<TemperatureUnit> availableTemperatureUnits = Arrays.asList(TemperatureUnit.values());
	private static final List<DatePattern> availableDatePatterns = Arrays.asList(DatePattern.values());
	private static final List<TimePattern> availableTimePatters = Arrays.asList(TimePattern.values());
	private User user;
	private UploadedFile importFile;
	private String token;
	@EJB
	private UserManager um;

	@EJB
	private CalendarManager cm;

	@PostConstruct
	public void init() {
		user = um.getLoggedUser();
	}

	public StreamedContent exportCalendar() {
		InputStream is = cm.xmlExport(user.getCalendar());
		DefaultStreamedContent sc = new DefaultStreamedContent(is);
		sc.setName(user.getEmail() + "_calendar.xml");

		return sc;
	}

	public void importCalendar() {
		FacesMessenger messenger = new FacesMessenger();

		if (importFile == null || importFile.getFileName().equals("")) {
			messenger.add("You have to select a file to import.", FacesMessage.SEVERITY_WARN);
			return;
		}

		try {
			cm.xmlImport(user.getCalendar(), importFile.getInputstream());
		} catch (IOException e) {
			LOGGER.log(Level.SEVERE, "Error getting input stream", e);
		} catch (CalendarManager.ImportCalendarException e) {
			messenger.add("Error importing calendar. The file may be corrupted or of a wrong type.", FacesMessage.SEVERITY_ERROR);
			return;
		}
		messenger.add("Calendar imported correctly.", FacesMessage.SEVERITY_INFO);
	}

	public UploadedFile getImportFile() {
		return importFile;
	}

	public void setImportFile(UploadedFile importFile) {
		this.importFile = importFile;
	}

	public List<String> getAvailableTimeZones() {
		return availableTimeZones;
	}

	public List<TemperatureUnit> getAvailableTemperatureUnits() {
		return availableTemperatureUnits;
	}

	public List<DatePattern> getAvailableDatePatterns() {
		return availableDatePatterns;
	}

	public List<TimePattern> getAvailableTimePatters() {
		return availableTimePatters;
	}

	public User getUser() {
		return user;
	}

	public String getToken() {
		return token;
	}

	public void setToken(String token) {
		this.token = token;
	}

	public String saveAction() {
		um.editUser(user);
		cm.editCalendar(user.getCalendar());
		return "/user/home?faces-redirect=true";
	}

	public String confirmEmail() {
		FacesMessenger messenger = new FacesMessenger();
		if (token == null || user.hasConfirmedEmail()) {
			return null;
		}
		try {
			um.confirmEmail(token);
			messenger.add("Email confirmed.");
		} catch (UserManager.ConfirmationException e) {
			messenger.add("The token you inserted is wrong", FacesMessage.SEVERITY_WARN);
		}

		user = um.getLoggedUser();

		return null;
	}

	public String reSendEmail() {
		FacesMessenger messenger = new FacesMessenger();

		try {
			um.reSendTokenEmail(user);
			messenger.add("Another email has been sent to " + user.getEmail());
		} catch (UserManager.FrequentReSendEmailException e) {
			messenger.add("You can resend the confirmation email only one time per hour. " +
					"You will be able to send another email at " +
					DateTimeUtils.format(e.getAvailableDate(), user.getTimePattern().getPattern(), user.getCalendar().getTimeZone()) + ".");
		}
		return null;
	}
}
